using Microsoft.EntityFrameworkCore.Storage;
using PowerManage.EntityFrameworkCore;

namespace PowerManage.Service.UOW;

/**
 * 实现IDisposable是为了 对象释放的时候，如果事务未提交，自动回滚事务
 */
public class UnitOfWork : IUnitOfWork, IDisposable
{
    /// <summary>
    /// 数据库上下文
    /// </summary>
    private readonly ApplicationDbContext _dbContext;

    /// <summary>
    /// 事务
    /// </summary>
    private IDbContextTransaction? _transaction = null;

    /// <summary>
    /// 是否提交事务
    /// </summary>
    private bool _isCommit = false;

    /// <summary>
    /// 构造器注入 将数据库上下文传递给UnitOfWork 为了管理事务
    /// </summary>
    /// <param name="dbContext"></param>
    public UnitOfWork(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    /// <summary>
    /// 开启事务
    /// </summary>
    public void BeginTransaction()
    {
        _transaction = _dbContext.Database.BeginTransaction();
    }

    /// <summary>
    /// 提交事务
    /// </summary>
    public void Commit()
    {
        if (_transaction != null)
        {
            _transaction?.Commit();
        }

        _isCommit = true;
    }

    /// <summary>
    /// 回滚事务
    /// </summary>
    public void Dispose()
    {
        if (_transaction != null && !_isCommit)
        {
            _transaction?.Rollback();
        }

        //无论是否提交，只要事务存在，都需要释放资源
        if (_transaction != null)
        {
            _transaction.Dispose();
        }
    }
}